import math

import torch.utils.model_zoo as model_zoo
from torch import nn

cfg = {
    11: [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    13: [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    16: [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    19: [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}

model_urls = {
    'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
    'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
    'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
    'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
    'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',
    'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',
    'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
    'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
}


class VGG(nn.Module):

    def __init__(self, num_layers: int, num_classes: int = 1000, pretrained: bool = False, freeze_stages: int = -1,
                 batch_norm: bool = False,
                 init_weights: bool = True):
        super().__init__()
        assert -1 <= freeze_stages <= 4, "Invalid argument freeze_stages {}".format(freeze_stages)
        self.num_classes = num_classes
        self.num_layers = num_layers

        feat_name = "vgg{}{}".format(num_layers, "_bn" if batch_norm else "")
        assert feat_name in model_urls, "{} is not supported!".format(feat_name)
        self.features = self._make_layer(cfg[num_layers], batch_norm=batch_norm)
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            nn.Linear(4096, num_classes),
        )

        if pretrained:
            self._load_weights(feat_name)
        else:
            if init_weights:
                self._initialize_weights()

        self._freeze_stages(freeze_stages)

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), -1)
        x = self.classifier(x)
        return x

    def _freeze_stages(self, freeze_stages):
        if freeze_stages != -1:
            for i in range(0, freeze_stages + 1):
                for param in self.features[i].parameters():
                    param.require_grad = False

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
                if m.bias is not None:
                    m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.Linear):
                m.weight.data.normal_(0, 0.01)
                m.bias.data.zero_()

    def _load_weights(self, feat_name):
        state_dict = model_zoo.load_url(model_urls[feat_name])
        mapping = {
            "features.stage_1.0.weight": "features.0.weight",
            "features.stage_1.0.bias": "features.0.bias",
            "features.stage_2.0.weight": "features.3.weight",
            "features.stage_2.0.bias": "features.3.bias",
            "features.stage_3.0.weight": "features.6.weight",
            "features.stage_3.0.bias": "features.6.bias",
            "features.stage_3.2.weight": "features.8.weight",
            "features.stage_3.2.bias": "features.8.bias",
            "features.stage_4.0.weight": "features.11.weight",
            "features.stage_4.0.bias": "features.11.bias",
            "features.stage_4.2.weight": "features.13.weight",
            "features.stage_4.2.bias": "features.13.bias",
            "features.stage_5.0.weight": "features.16.weight",
            "features.stage_5.0.bias": "features.16.bias",
            "features.stage_5.2.weight": "features.18.weight",
            "features.stage_5.2.bias": "features.18.bias",
            'classifier.0.weight': 'classifier.0.weight',
            'classifier.0.bias': 'classifier.0.bias',
            'classifier.3.weight': 'classifier.3.weight',
            'classifier.3.bias': 'classifier.3.bias',
            'classifier.6.weight': 'classifier.6.weight',
            'classifier.6.bias': 'classifier.6.bias'
        }

        if self.num_classes == 1000:
            new_state_dict = dict([name, state_dict[to]] for name, to in mapping.items())
            self.load_state_dict(new_state_dict)
        else:
            mapping.pop('classifier.0.weight')
            mapping.pop('classifier.0.bias')
            mapping.pop('classifier.3.weight')
            mapping.pop('classifier.3.bias')
            mapping.pop('classifier.6.weight')
            mapping.pop('classifier.6.bias')
            new_state_dict = dict([name, state_dict[to]] for name, to in mapping.items())
            self.load_state_dict(new_state_dict, strict=False)

    def _make_layer(self, cfg, batch_norm=False):
        layers = []
        in_channels = 3
        current_stage = 0

        stages = nn.Sequential()
        for v in cfg:
            if v == 'M':
                current_stage += 1
                layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
                stages.add_module("stage_%d" % (current_stage), nn.Sequential(*layers))
                layers = []
            else:
                conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
                if batch_norm:
                    layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
                else:
                    layers += [conv2d, nn.ReLU(inplace=True)]
                in_channels = v
        return stages
